﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace WpfApp
{
    /// <summary>
    /// WPF默认没有Program，需要在属性内设置启动对象
    /// 全局异常处理在APP.xaml.cs内添加
    /// </summary>
    static class Program
    {
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(int hWnd, int cmdShow);

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32")]
        static extern int SetForegroundWindow(int hwnd);

        //private const int SW_HIDE = 0; 　　//从任务栏隐藏
        //private const int SW_NORMAL = 1;    //正常弹出窗体 
        //private const int SW_MAXIMIZE = 3;    //最大化弹出窗体 
        //private const int SW_SHOWNOACTIVATE = 4; 　　//激活窗体/恢复窗体/还原窗体
        //private const int SW_SHOW = 5; 　　//显示窗体，最小化时不会最大化
        //private const int SW_MINIMIZE = 6; 　　//最小化
        //private const int SW_RESTORE = 9;
        //private const int SW_SHOWDEFAULT = 10;

        private const int cmdShow = 4;

        [STAThread]
        static void Main(string[] args)
        {
            HY.Common.LogHelper.Info("程序启动");
            string processName = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(processName);
            if (processes.Length > 1)
            {
                //此处根据要显示窗体的Title属性值查找
                int mainHandle = FindWindow(null, "MainWindow");
                if (mainHandle != 0)
                {
                    ShowWindowAsync(mainHandle, cmdShow);
                    SetForegroundWindow(mainHandle);
                }
                Environment.Exit(0);
            }
            try
            {
                App app = new App();
                app.InitializeComponent();
                app.Run();
            }
            catch (Exception ex)
            {
                HY.Common.LogHelper.Error("程序运行中出错", ex);
            }
        }
    }
}
